package com.zhiyou100.review.day021.homework.homework6;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @packageName: MySender
 * @className: com.zhiyou100.review.day021.homework.homework6
 * @Description: TODO 发送者
 * @author: yang
 * @date: 7/2/20
 */
public class MySender {
    private static final String IP = "127.0.0.1";
    private static final int ACCEPT_PORT = 10086;
    private static final int SEND_PORT = 10000;

    public static void main(String[] args) throws Exception {
        DatagramSocket datagramSocket = new DatagramSocket(SEND_PORT);
        while (true) {

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            // 获取键盘的输入
            String readLine = bufferedReader.readLine();
            // 读一行

            byte[] bytes = readLine.getBytes();
            DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getByName(IP), ACCEPT_PORT);
            // 封装

            datagramSocket.send(datagramPacket);
            // 发送

            if (readLine.endsWith("END")) {
                // 结束
                break;
            }

            DatagramPacket datagramPacket1 = new DatagramPacket(bytes, 0, bytes.length);
            datagramSocket.receive(datagramPacket1);

            int n = datagramPacket1.getLength();
            String s = new String(bytes, 0, n);
            System.out.println("接受到 " + datagramPacket1.getAddress() + " 的消息" + s);
            if (s.endsWith("END")) {
                break;
            }
        }
        datagramSocket.close();
    }
}
